<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;
use addons\epay\library\Service;
use Yansongda\Pay\Pay;
use think\Cache;
use think\Config;
use fast\Http;


/**
 * 订单管理
 *
 * @icon fa fa-circle-o
 */
class Order extends Backend
{

    /**
     * Order模型对象
     * @var \app\admin\model\Order
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Order;

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['user','master','install','repair'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {
                $row->getRelation('user')->visible(['nickname']);
                $row->getRelation('master')->visible(['nickname']);
//                $row->getRelation('repair')->visible(['nickname']);
                $province = \app\admin\model\Area::where(['id'=>$row['province_id']])
                    ->value('name');
                $city = \app\admin\model\Area::where(['id'=>$row['city_id']])
                    ->value('name');
                $area = \app\admin\model\Area::where(['id'=>$row['area_id']])
                    ->value('name');
                $row['region'] = $province.'/'.$city.'/'.$area;

            }

            $total = $this->model->with(['user','install','repair'])->where($where)->where(['order.paid'=>1,'refund_status'=>0])->order($sort, $order)->sum('order.payamount');
            $payment = $this->model->with(['user','install','repair'])->where($where)->where(['order.paid'=>1,'order.status'=>['in',[0,1,2,3],'refund_status'=>0]])->order($sort, $order)->sum('order.payamount');
            $order_ids = $this->model->with(['user','install','repair'])->where($where)->where(['order.paid'=>1,'refund_status'=>0])->order($sort, $order)->column('order.id');
            $addon = \app\admin\model\OrderInstall::where(['order_id'=>['in',$order_ids]])->sum('extra_money');
//            $chargeback = $this->model->with(['user','install','repair'])->where($where)->where(['order.status'=>['in', [100]]])->order($sort, $order)->sum('order.payamount');

            $result = array("total" => $list->total(), "rows" => $list->items(), "extend" => ['total' => $total, 'payment' => $payment, 'addon' => $addon]);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }

            // 补充订单数据
            $params['order_no'] = getNewOrderNo();
            $params['payamount'] = $params['amount'];
            $params['province_id'] = $this->request->post('province');
            $params['city_id'] = $this->request->post('city');
            $params['area_id'] = $this->request->post('area');
            $params['paid'] = 1;
            $params['paytime'] = time();
            $params['is_sure'] = 1;
            // 保存订单
            $result = $this->model->allowField(true)->save($params);

            if($params['type'] == 'install'){
                // 准备安装订单数据
                $power = \app\admin\model\PowerType::get($params['power_id']);
                $package = \app\admin\model\Package::get($params['package_id']);
                $package_type = \app\admin\model\PackageType::get($params['package_type_id']);
                $params_install = [
                    'order_id'  => $this->model->id,
                    'power_id'      =>  $params['power_id'],
                    'power_name'      =>  $power['name'],
                    'package_id'      =>  $params['package_id'],
                    'package_name'      =>  $package['name'],
                    'package_type_id'      =>  $params['package_type_id'],
                    'package_type_name'      =>  $package_type['name'] . '(' . $package_type['type'] .')' ,
                    'price'      =>  $params['amount'],
                ];
                // 创建安装订单
                \app\admin\model\OrderInstall::create($params_install);
            }

            if($params['type'] == 'repair'){
                // 准备安装订单数据
                $params_repair = [
                    'order_id'  => $this->model->id,
                    'device_name'      =>  $params['device_name'],
                    'device_model'      =>  $params['device_model'],
                    'repair_type'      =>  $params['repair_type'],
                    'title'      =>  $params['title'],
                    'description'      =>  $params['description'],
                    'annex'      =>  $params['annex'],
                ];
                // 创建安装订单
                \app\admin\model\OrderRepair::create($params_repair);
            }


            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            if($row['type'] == 'install'){
                $install = \app\admin\model\OrderInstall::where(['order_id'=>$row['id']])->find();
                $row['power_name'] = \app\admin\model\PowerType::where(['id'=>$install['power_id']])->value('name');
                $row['package_name'] = \app\admin\model\Package::where(['id'=>$install['package_id']])->value('name');
                $row['package_type_name'] = \app\admin\model\PackageType::where(['id'=>$install['package_type_id']])->value('name');
                $row['device_name'] = '';
                $row['device_model'] = '';
                $row['repair_type'] = '';
                $row['title'] = '';
                $row['description'] = '';
                $row['annex'] = '';
            }

            if($row['type'] == 'repair'){
                $repair = \app\admin\model\OrderRepair::where(['order_id'=>$row['id']])->find();
                $row['power_name'] = '';
                $row['package_name'] = '';
                $row['package_type_name'] = '';
                $row['device_name'] = $repair['device_name'];
                $row['device_model'] = $repair['device_model'];
                $row['repair_type'] = $repair['repair_type'];
                $row['title'] = $repair['title'];
                $row['description'] = $repair['description'];
                $row['annex'] = $repair['annex'];
            }
            $row['finish_annex'] = json_decode($row['finish_annex'],true);

            if($row['master_id']){
                $master = \app\admin\model\User::get($row['master_id']);
                $row['master_name'] = $master['nickname'];
                $row['master_mobile'] = $master['mobile'];
            }else{
                $row['master_name'] = '';
                $row['master_mobile'] = '';
            }
            $row['province'] = \app\admin\model\Area::where(['id'=>$row['province_id']])->value('name');
            $row['city'] = \app\admin\model\Area::where(['id'=>$row['city_id']])->value('name');
            $row['area'] = \app\admin\model\Area::where(['id'=>$row['area_id']])->value('name');

            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    public function confirm($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $params['is_sure'] = 1;
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    public function allocated()
    {
        $id = $this->request->post('id');
        $master_id = $this->request->post('master_id');

        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            
            
            $fw_appid = 'wx10c0a62d50d33610';
            $fw_secret = '8c1231e8a8fc7aa5d6fe1f009db14aef';
            $ts_openid = \app\admin\model\User::where(['id'=>$master_id])->value('ts_openid');
            if(!$ts_openid){
                // 获取关注者列表
                $list = json_decode(Http::get('https://api.weixin.qq.com/cgi-bin/user/get?access_token=' . $this->getFwhAccessToken($fw_appid,$fw_secret) . '&next_openid='),true);
                
                if($list['total'] > 1000){
                    $num = ceil($list['total']/1000);
                    $openid_list = [];
                    for($i=1;$i<=$num;$i++){
                        $k = $list['count'] - 1;
                        $list = json_decode(Http::get('https://api.weixin.qq.com/cgi-bin/user/get?access_token=' . $this->getFwhAccessToken($fw_appid,$fw_secret) . '&next_openid=' . $list['data'][$k]),true);
                        $openid_list += $list['data']['openid'];
                    }
                }else{
                    $openid_list = $list['data']['openid'];
                }
                
                $ts_openid = '';
                foreach($openid_list as $openid){
                    $res = json_decode(Http::get('https://api.weixin.qq.com/cgi-bin/user/info?access_token='.$this->getFwhAccessToken($fw_appid,$fw_secret).'&openid='.$openid.'&lang=zh_CN'),true);
                    // return $res;
                    $userInfo = \app\admin\model\User::where(['unionid'=>$res['unionid']])->find();
                    
                    $ts_openid = $openid;
                    \app\admin\model\User::where(['unionid'=>$res['unionid']])->update(['ts_openid'=>$ts_openid]);
                    break;
                }
            }
            
            // return $ts_openid;
            
            
            // 发送推送
            // 获取accesstoken
            $app_id = Config::get('site.miniappid');
            $app_secret = Config::get('site.minisecret');
            $orderInfo = \app\admin\model\Order::where(['id'=>$id])->find();
            
            if($orderInfo['type'] == 'install') {
                $service_name = \app\admin\model\OrderInstall::where(['order_id'=>$orderInfo['id']])->value('power_name');
            }else{
                $service_name = '维修充电桩';
            }
            
            $data_template = [
                "thing14" => ["value" => $orderInfo['name']],// 客户名称
                "thing18" => ["value" => $service_name],// 服务名称 
                "thing17" => ["value" => mb_substr($orderInfo['address'], 0, 14, 'utf-8') . "..."],// 客户地址，超过16个字。。。
            ];
            // return $unionid;
            $accesstoken = $this->sendMessageWithAccessToken($fw_appid, $fw_secret, 'cFKsMwUUBxne60kD8rzpwRr7pnxfMloWUe8fupNyGkg', $ts_openid, $data_template);
            // return $accesstoken;
            
            $result = $this->model->where(['id'=>$id])->update(['master_id'=>$master_id,'status'=>1]);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success('操作成功');
    }

    public function transfer()
    {
        $id = $this->request->post('id');
        $master_id = $this->request->post('master_id');

        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }

            $result = $this->model->where(['id'=>$id])->update(['master_id'=>$master_id]);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success('操作成功');
    }

    public function cancel($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            if($row['type'] == 'install'){
                $install = \app\admin\model\OrderInstall::where(['order_id'=>$row['id']])->find();
                $row['title'] = "{$install['power_name']}({$install['package_name']})【{$install['package_type_name']}】";

            }

            if($row['type'] == 'repair'){
                $repair = \app\admin\model\OrderRepair::where(['order_id'=>$row['id']])->find();

                $row['title'] = "{$repair['device_name']}({$repair['device_model']})【{$repair['title']}】";
            }
            if($row['old_state'] == 0){
                // 全退
                $row['refund'] = $row['payamount'];
            }
            elseif($row['old_state'] == 1){
                // 扣除上门费
                $feeInfo = \app\admin\model\RepairFee::where(['status'=>'normal'])->select();
                $callout_fee = 0;$inspection_fee = 0;
                foreach ($feeInfo as $item){
                    if($item['title'] == '上门费')  $callout_fee = $item['value'];
                    if($item['title'] == '检修费')  $inspection_fee = $item['value'];
                }
                $row['refund'] = $row['payamount'] - $callout_fee;
            }
            elseif($row['old_state'] == 2 || $row['old_state'] == 3){
                // 扣除上门费和检修费
                $feeInfo = \app\admin\model\RepairFee::where(['status'=>'normal'])->select();
                $callout_fee = 0;$inspection_fee = 0;
                foreach ($feeInfo as $item){
                    if($item['title'] == '上门费')  $callout_fee = $item['value'];
                    if($item['title'] == '检修费')  $inspection_fee = $item['value'];
                }
                $row['refund'] = $row['payamount'] - $callout_fee -  $inspection_fee;
            }else{
                // 全退
                $row['refund'] = $row['payamount'];
            }
            if($row['refund'] <= 0)
            {
                $row['refund'] = 0;
            }
            if($row['paid'] == 0){
                $row['refund'] = 0;
            }

            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $amount = $params['refund'] * 100;
            if($amount > 0){
                // $amount = 1;// 测试阶段，正式上线记得关闭
                $order_no = $params['order_no'];
                
                // 退款
                $result = $this->Refund('',$order_no,$amount);
                if($result['code'] != 1){
                    $this->error($result['msg']);
                }
            }
            $params['refund_status'] = 1;
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    public function cancel_master($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }

        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $params['master_id'] = 0;
            $params['status'] = 0;
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function map($ids = null)
    {

        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $id = $this->request->get('id');
            $row = $this->model->get($id);

            if(isset($row['master_id'])){
                $markers = json_encode([
                    [$row['master_lng'],$row['master_lat']]
                ]);

            }else{
                $markers = json_encode([]);
            }
            $this->view->assign('lng',$row['address_lng']);
            $this->view->assign('lat',$row['address_lat']);
            $this->view->assign('markers',$markers);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }
    



    //退款
    public function Refund($transaction_id,$out_trade_no,$amount){ //商户订单号,微信生成的退款订单号 二选一即可
        $time=time();
        $out_refund_no=$time.rand(1111,9999);
        $refundData=[
            'out_refund_no'=>$out_refund_no,
            'reason'=>'用户取消订单',
            // 'notify_url'=>$this->config['refund_notify_url'],
            'funds_account'=>'AVAILABLE',
            'amount'=>[
                'refund'=>$amount, //退款标价金额，单位为分，可以做部分退款
                'total'=>$amount, //订单总金额，单位为分
                'currency'=>'CNY'
            ]
        ];
        if(!$transaction_id){ //商户订单号,微信生成的退款订单号 二选一即可
            if(!$out_trade_no){
                return ['code'=>0,'msg'=>'退款订单号不能为空'];
            }else{
                $refundData['out_trade_no']=$out_trade_no;
            }
        }else{
            $refundData['transaction_id']=$transaction_id;
        }
        $url='https://api.mch.weixin.qq.com/v3/refund/domestic/refunds';
        $urlarr = parse_url($url); //拆解为：[scheme=>https,host=>api.mch.weixin.qq.com,path=>/v3/pay/transactions/native]
        $mchid = '1709517563';//商户ID
        $xlid = '4C59EB16EAA829C2E0DEC4244E6C41633768D1DF';//证书序列号
        $refundData=json_encode($refundData);
        $nonce = $this->getNonceStr();
        $key = $this->getSign($refundData,$urlarr['path'],$nonce,$time);
        $token = sprintf('mchid="%s",serial_no="%s",nonce_str="%s",timestamp="%d",signature="%s"',$mchid,$xlid,$nonce,$time,$key);
        $header  = array(
            'Accept: application/json',
            'Content-Type: application/json',
            'User-Agent:*/*',
            'Authorization: WECHATPAY2-SHA256-RSA2048 '.$token
        );
        $res=$this->curl_post_https($url,$refundData,$header);
        $res_array=json_decode($res,true);
        if(isset($res_array['status'])){
            if($res_array['status']=='PROCESSING' || $res_array['status']=='SUCCESS'){
                return ['code'=>1,'msg'=>'退款成功'];
            }else{
                return ['code'=>0,'msg'=>$res_array['message']];
            }
            
        }else{
            return ['code'=>0,'msg'=>$res_array['message']];
        }
    }
    
    
    //获取随机字符串
    public function getNonceStr(){
        $strs="QWERTYUIOPASDFGHJKLZXCVBNM1234567890";
        $name=substr(str_shuffle($strs),mt_rand(0,strlen($strs)-11),32);
        return $name;
    }

    //微信支付签名
    function getSign($data=array(),$url,$randstr,$time){
        $str = "POST"."\n".$url."\n".$time."\n".$randstr."\n".$data."\n";
        $key = file_get_contents(ROOT_PATH . '/addons/epay/certs/apiclient_key.pem');//在商户平台下载的秘钥,读取到变量
        $str = $this->getSha256WithRSA($str,$key);
        return $str;
    }

    //调起支付的签名
    function getWechartSign($appid,$timeStamp,$noncestr,$prepay_id){
        $str = $appid."\n".$timeStamp."\n".$noncestr."\n".$prepay_id."\n";
        $key = file_get_contents(ROOT_PATH . '/addons/epay/certs/apiclient_key.pem');//在商户平台下载的秘钥,读取到变量
        $str = $this->getSha256WithRSA($str,$key);
        return $str;
    }

    //加密
    public function getSha256WithRSA($content, $privateKey){
        $binary_signature = "";
        $algo = "SHA256";
        openssl_sign($content, $binary_signature, $privateKey, $algo);
        $sign = base64_encode($binary_signature);
        return $sign;
    }

    /* PHP CURL HTTPS POST */
    function curl_post_https($url,$data,$header){ // 模拟提交数据函数
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); // 从证书中检查SSL加密算法是否存在，如果出错则修改为0，默认为1
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        $tmpInfo = curl_exec($curl); // 执行操作
        if (curl_errno($curl)) {
            echo 'Errno'.curl_error($curl);//捕抓异常
        }
        curl_close($curl); // 关闭CURL会话
        return $tmpInfo; // 返回数据，json格式
    }
    
    
    
    // 刷新access_token
    private function getAccessToken($appid, $appsecret)
    {
        // return 123;
        $access_token = Cache::get('access_token');
        if($access_token){
            return $access_token;
        }
        
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appsecret";

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $response = curl_exec($ch);
        curl_close($ch);

        $data = json_decode($response, true);
        if (isset($data['access_token'])) {
            Cache::set('access_token',$data['access_token'],7200);
            return $data['access_token'];
        } else {
            return false;
        }
    }
    
    private function getFwhAccessToken($appid, $appsecret)
    {
        // return 123;
        $access_token = Cache::get('fwh_access_token');
        if($access_token){
            return $access_token;
        }
        
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appsecret";

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $response = curl_exec($ch);
        curl_close($ch);

        $data = json_decode($response, true);
        if (isset($data['access_token'])) {
            Cache::set('fwh_access_token',$data['access_token'],7200);
            return $data['access_token'];
        } else {
            return false;
        }
    }

    
    // 发送订阅消息
    public function sendMessageWithAccessToken($appid, $appsecret, $template_id, $openid, $data_template)
    {
        
        $access_token = $this->getFwhAccessToken($appid, $appsecret);
        // return $access_token;
        // 发送订阅消息的接口
        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=$access_token";
        
        // 需要发送的消息体
        $message_data = [
            "touser" => $openid,
            "template_id" => $template_id,
            "miniprogram" => [
                "appid"=>"wxa8e0ec7b7f70bdc7",
                "pagepath"=>"/pagesA/mineSub/orderList?type=-1"
            ],
            // "page" => "pages/read/read?aid=360282",
            // "miniprogram" => "formal",
            // "lang" => "zh_CN",
            "data" => $data_template
        ];
        
        // 初始化cURL
        $ch = curl_init();
        
        // 配置cURL
        curl_setopt_array($ch, [
            CURLOPT_URL => $url,
            CURLOPT_POST => 1,
            CURLOPT_POSTFIELDS => json_encode($message_data),
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER => ['Content-Type: application/json']
        ]);
        
        // 执行cURL
        $response = curl_exec($ch);
        
        // 判断发送结果
        if (curl_errno($ch)) {
            
            // 失败
            echo '执行失败: ' . curl_error($ch);
        } else {
            
            // 成功
            echo '执行成功: ' . $response;
        }
        
        // 关闭cURL
        curl_close($ch);
    }

    

}


